package com.peng._05weibo.controller;

import com.peng._05weibo.common.response.JsonResult;
import com.peng._05weibo.common.response.StatusCode;
import com.peng._05weibo.mapper.UserMapper;
import com.peng._05weibo.pojo.dto.UserLoginDTO;
import com.peng._05weibo.pojo.dto.UserRegDTO;
import com.peng._05weibo.pojo.entity.User;
import com.peng._05weibo.pojo.vo.UserVO;
import com.peng._05weibo.util.MyMD5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 用户控制类
 *
 * @Author peng
 * @Date 2024-04-23 11:36
 */
@RestController
@RequestMapping("/v1/users")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册接口
     *
     * @param userRegDTO 用户注册表单数据
     * @return 1-成功 2-用户名占用
     * @throws Exception
     */
    @ApiOperation("用户注册")
    @PostMapping("/reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO) throws Exception {
        System.out.println("userRegDTO = " + userRegDTO);
        /**  注册步骤
          * 1.接收参数
          * todo 2.校验数据合法性
          * 3.校验用户名是否被占用
          *     3.1 占用 code-1004
          *     3.2 未占用 code-1001
         */
        UserVO userVO = userMapper.selectUserByUsername(userRegDTO.getUsername());
        if (userVO != null) {
            System.out.println("用户名被占用");
            return new JsonResult(StatusCode.USERNAME_OCCUPIED);
        }
        User user = User.builder()
                .nickname(userRegDTO.getNickname())
                .username(userRegDTO.getUsername())
                .password(MyMD5Util.getEncryptedPwd(userRegDTO.getPassword()))
                .created(new Date())
                .build();
        int i = userMapper.insertUser(user);
        if (i > 0){
            return JsonResult.success("注册成功");
        } else {
            return JsonResult.error("注册失败");
        }

    }
    /**
     * 用户登录接口
     *
     * @param userLoginDTO 用户登录表单数据
     * @param httpSession  httpSession会话保持
     * @return 1-成功 2-密码错误 3-用户不存在
     * @throws Exception
     */
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, HttpSession httpSession) throws Exception {
        UserVO userVO = userMapper.selectUserByUsername(userLoginDTO.getUsername());
        if (userVO == null) {
            System.out.println("用户不存在或用户名错误");
            return new JsonResult(StatusCode.WRONG_USERNAME);
        }
        boolean validPwd = MyMD5Util.validPassword(userLoginDTO.getPassword(), userVO.getPassword());
        if (validPwd) {
            System.out.println("登录成功");
            // 登录成功后，将用户信息存入session中
            httpSession.setAttribute("user", userVO);
            return new JsonResult(StatusCode.LOGIN_SUCCESS);
        } else {
            System.out.println("密码错误");
            return new JsonResult(StatusCode.WRONG_PASSWORD);
        }
    }

    /**
     * 获取当前用户接口
     *
     * @param httpSession session
     * @return 当前用户信息UserVO
     */
    @ApiOperation("获取当前用户接口")
    @GetMapping("/currentUser")
    public JsonResult getCurrentUser(HttpSession httpSession) {
        // 从session中获取用户信息
        return JsonResult.success((UserVO) httpSession.getAttribute("user"));

    }

    /**
     * 退出登录接口
     *
     * @param httpSession
     */
    @ApiOperation("退出登录接口")
    @GetMapping("/logout")
    public JsonResult logout(HttpSession httpSession) {
        httpSession.removeAttribute("user");
        return JsonResult.success("退出登录成功");
    }
}
